package com.zengraoli.PointSystem.controller;

import com.zengraoli.PointSystem.model.bo.PointSystemConsumePointsInputBO;
import com.zengraoli.PointSystem.model.bo.PointSystemGetBalanceInputBO;
import com.zengraoli.PointSystem.model.bo.PointSystemIssuePointsInputBO;
import com.zengraoli.PointSystem.model.bo.PointSystemTransferPointsInputBO;
import com.zengraoli.PointSystem.service.PointSystemService;
import com.zengraoli.PointSystem.utils.JsonData;
import lombok.extern.slf4j.Slf4j;
import org.fisco.bcos.sdk.transaction.model.dto.CallResponse;
import org.fisco.bcos.sdk.transaction.model.dto.TransactionResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Objects;

@Slf4j
@Controller
@RequestMapping("/api/v1/pointsystem")
public class PointSystemController {
    @Autowired
    PointSystemService pointSystemService;

    // 获取admin地址
    @GetMapping("/admin")
    @ResponseBody
    public JsonData admin() throws Exception {
        long startTime = System.currentTimeMillis();
        CallResponse response = pointSystemService.admin();
        String addr = String.valueOf(response.getReturnABIObject().get(0).getStringValue());
        long endTime = System.currentTimeMillis();
        log.info("获取管理员地址耗时: {}ms", endTime - startTime);
        return JsonData.buildSuccess(addr, "admin addr select successed.");
    }

    // 查询余额
    @GetMapping("/getBalance")
    @ResponseBody
    public JsonData getBalance(@RequestParam String caller) throws Exception {
        long startTime = System.currentTimeMillis();
        log.info("开始处理getBalance请求，用户: {}", caller);
        try {
            PointSystemGetBalanceInputBO pointSystemGetBalanceInputBO = new PointSystemGetBalanceInputBO(caller);
            log.debug("构建输入参数: {}", pointSystemGetBalanceInputBO);

            CallResponse response = pointSystemService.getBalance(pointSystemGetBalanceInputBO);
            int balance = response.getReturnABIObject().get(0).getNumericValue().getValue().intValue();

            long endTime = System.currentTimeMillis();
            log.info("获取余额成功，耗时: {}ms，返回结果: {}", endTime - startTime, balance);

            JsonData result = JsonData.buildSuccess(balance, "查询余额成功");
            return result;
        } catch (Exception e) {
            log.error("获取余额失败，原因: ", e);
            return JsonData.buildError("查询余额失败: " + e.getMessage());
        }
    }

    // 充值积分（异步处理）
    @PostMapping("/issuePoints")
    @ResponseBody
    public JsonData issuePoints(@RequestBody @Valid PointSystemIssuePointsInputBO input, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return JsonData.buildError(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
        try {
            TransactionResponse response = pointSystemService.issuePoints(input);
            int res = response.getReturnABIObject().get(0).getNumericValue().getValue().intValue();
            return JsonData.buildSuccess(res, "Success to issuePoints.");
        } catch (Exception e) {
            log.error("Error issuePoints: ", e);
            return JsonData.buildError("Failed to issuePoints.");
        }
    }

    // 积分消费（异步处理）
    @PostMapping("/consumePoints")
    @ResponseBody
    public JsonData consumePoints(@RequestBody @Valid PointSystemConsumePointsInputBO input, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return JsonData.buildError(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
        try {
            TransactionResponse response = pointSystemService.consumePoints(input);
            if (response.getReturnCode() == 22) {
                return JsonData.buildError(response.getReturnMessage());
            }
            return JsonData.buildSuccess(response.getReturnABIObject().get(0).getNumericValue().getValue().intValue(), "Success to issuePoints.");
        } catch (Exception e) {
            log.error("Error consumePoints: ", e);
            return JsonData.buildError("Failed to consumePoints.");
        }
    }

    // 积分转账（异步处理）
    @PostMapping("/transferPoints")
    @ResponseBody
    public JsonData transferPoints(@RequestBody @Valid PointSystemTransferPointsInputBO input, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return JsonData.buildError(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
        try {
            TransactionResponse response = pointSystemService.transferPoints(input);
            if (response.getReturnCode() == 22) {
                return JsonData.buildError(response.getReturnMessage());
            }
            return JsonData.buildSuccess(response.getReturnABIObject().get(0).getNumericValue().getValue().intValue(), "Success to transferPoints.");
        } catch (Exception e) {
            log.error("Error transferPoints: ", e);
            return JsonData.buildError("Failed to transferPoints.");
        }
    }
}
